/*
 * 工程index
 * @Author: ljb
 * @Date: 2018-11-13 15:00:41
 * @Last Modified by: kanglin
 * @Last Modified time: 2019-03-05 11:32:51
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>

	@import '~src/assets/css/common.less';

	.v-index {
		width: 100%;
		background-color: #F9F9F9;
	}
</style>
<template>
	<div
		class="v-index">

		<!-- 区域模块组件 -->
		<component
			v-for="app_module in app_home_setting"
			:key="app_module.layout_module_id"
			:is="block_map[app_module.code]"
			:code="app_module.code"
			:setting="app_module.setting"
			:layout-module-id="app_module.layout_module_id"
			@search="moduleSearch"
			@link="linkTo"/>

	</div>
</template>
<script>

import * as API_LIST from 'src/API_LIST';

import qs from 'qs';
import { mapMutations, mapGetters } from 'vuex';
import banner from 'src/views/module/banner-module';
import navs from 'src/views/module/navs-module';
import singleProduct from 'src/views/module/single-product-module';
import specialProduct from 'src/views/module/special-product-module';
import recommendProduct from 'src/views/module/recommend-product-module';
import articleModule from 'src/views/module/article-module';
import bestseller from 'src/views/module/bestseller-module';

import { appHandle } from 'src/views/mixins/appHandle';
// import { importStyle } from 'src/utils/dom-helper';

/* disable-eslint */
/**
 * 首页
 * @vue-data {Object} block_map 模块名称的映射表
 * @vue-data {array} app_home_setting 首页模块数组
 */
export default {
	components: {
		banner,
		navs,
		singleProduct,
		recommendProduct,
		articleModule,
		bestseller,
		specialProduct,
	},
	mixins: [appHandle],
	data() {
		return {
			block_map: {
				slideshow: 'banner',
				panx_app_icon_link: 'navs',
				latest: 'singleProduct',
				special: 'specialProduct',
				featured: 'recommendProduct',
				press_latest: 'articleModule',
				bestseller: 'bestseller',
			},	// 区域模块映射表

			app_home_setting: [],		// 首页模块数组
		};
	},
	computed: {
		...mapGetters(['getThemeName']),
	},
	created() {
		this.fetchModule();
	},
	methods: {

		...mapMutations(['setThemeName']),

		/**
		 * 从url读取模拟的主题
		 */
		readMockThemeName() {
			const query = qs.parse(window.location.search.replace(/^\?/, ''));
			return query.theme ? query.theme : '';
		},

		/**
		 * 产品专区模块跳转 更多
		 * @param  {Object} [params={}] 需要传递的参数
		 */
		moduleSearch(params = {}) {
			Object.assign(params, { theme: this.getThemeName });
			const queryString = qs.stringify(params);
			const { origin, pathname, search } = window.location;
			const url = `${origin + pathname + search}#/more?${queryString}`;
			const jsonString = JSON.stringify({ url });
			this.handleApp('more', jsonString);
			// this.$router.push({ path: '/more', query: params });
		},
		/**
		 * 跳转链接
		 * @param  {string} href 链接地址
		 */
		linkTo(href) {
			let open_url;

			if (!href) return;

			if (this.isAppProtocol(href)) {
				const [app_fn, query_string] = href.split('://').pop().split('?');
				const params = qs.parse(query_string, { arrayFormat: 'indices' }) || {};
				this.handleApp(app_fn, JSON.stringify(params));
			} else if (this.isUrlProtocol(href)) {
				window.location.href = href;
			} else {
				open_url = `${window.location.protocol}//${href}`;
				window.location.href = open_url;
			}
		},

		/**
		 * 是否为正常网址协议（http/https）
		 * @param  {String} url 需要进行判断的url
		 * @return {Boolean} true代表是正常的网址，反之不是
		 */
		isUrlProtocol(url) {
			const protocol = url.split('://').shift();

			const valid_protocol = ['http', 'https'];

			return valid_protocol.indexOf(protocol) !== -1;
		},

		/**
		 * 是否为app自定义协议
		 * @param  {String} url {需要进行判断的url}
		 * @return {Boolean} true代表是app自定义协议，反之不是
		 */
		isAppProtocol(url) {
			const protocol = url.split('://').shift();

			const app_valid_protocol = ['app'];

			return app_valid_protocol.indexOf(protocol) !== -1;
		},

		/**
		 * 获取首页模块
		 * @return {promise} 请求模块的promise
		 */
		fetchModule() {
			const param = {
				language: this.$url.language || this.$url.lang,
				store_id: this.$url.store_id,
				layout_route: 'app',
				currency: this.$url.currency,
			};

			const query_str = qs.stringify(param);

			return this.$http.get(`${API_LIST.HOME_MODULE}?${query_str}`)
				.then(({ data }) => {
					if (data.code !== 0) throw new Error(data.error);

					this.app_home_setting = data.app_home_setting;

					// importStyle(data.theme);
					const mock_theme = this.readMockThemeName();
					this.setThemeName(mock_theme || data.theme);
				})
				.catch((err) => {
					const toast = this.$createToast({
						type: 'error',
						time: 2000,
						txt: err.message,
					});
					toast.show();
				});
		},
	},
};
</script>
